import { Table, Tag, Typography, Space, Card, Row, Col, Statistic, Input, Button, Select } from '@/utils/antd-imports';
import { CheckOutlined, CloseOutlined, SearchOutlined, DollarOutlined } from '@/utils/icons';
import React, { useState } from 'react';

const { Option } = Select;
const { Text } = Typography;

const OutputValueTab = ({ subProjectsData }) => {
  const [searchText, setSearchText] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');

  // 生成产值数据
  const generateOutputValueData = () => {
    const outputValueData = [];
    
    subProjectsData.forEach(subProject => {
      const memberCount = Math.floor(Math.random() * 3) + 3;
      for (let i = 0; i < memberCount; i++) {
        const types = ['公司自由人', '正式员工', '外协人员', '临时工'];
        const businessTypes = ['设计', '施工', '监理', '咨询'];
        const hasOrder = Math.random() > 0.5;
        
        const workHours = Math.floor(Math.random() * 160) + 40; // 40-200小时
        const unitPrice = Math.floor(Math.random() * 200) + 100; // 100-300元/小时
        const deduction = Math.floor(Math.random() * 1000) + 500; // 500-1500元扣减
        const monthlyOutput = workHours * unitPrice - deduction;
        const monthlyOutputNoTax = monthlyOutput * 0.9; // 假设税率10%
        
        outputValueData.push({
          id: `${subProject.id}-${i}`,
          subProjectId: subProject.id,
          subProjectName: subProject.name,
          serialNumber: i + 1,
          employeeId: `E${String(i + 1).padStart(4, '0')}`,
          name: `员工${i+1}`,
          employeeType: types[Math.floor(Math.random() * types.length)],
          projectName: subProject.name,
          accountPeriod: '2024-01',
          projectCode: subProject.code || `P${String(subProject.id).padStart(6, '0')}`,
          projectManager: `项目经理${i+1}`,
          department: `部门${i+1}`,
          projectLocation: '北京',
          joinDate: '2023-01-01',
          projectJoinDate: subProject.startDate,
          projectLeaveDate: subProject.endDate,
          resignationDate: subProject.endDate,
          businessType: businessTypes[Math.floor(Math.random() * businessTypes.length)],
          hasOrder: hasOrder,
          unitPriceWithTax: unitPrice,
          workHours: workHours,
          deduction: deduction,
          monthlyOutput: monthlyOutput,
          monthlyOutputNoTax: monthlyOutputNoTax,
          salaryCost: Math.floor(monthlyOutput * 0.3), // 工资成本30%
          socialInsurance: Math.floor(monthlyOutput * 0.1), // 企业社保公积金10%
          otherFees: Math.floor(monthlyOutput * 0.05), // 其他费用5%
          commercialInsurance: Math.floor(monthlyOutput * 0.02), // 商保2%
          equipmentCost: Math.floor(monthlyOutput * 0.08), // 设备费用8%
          compensationAmount: Math.floor(monthlyOutput * 0.01), // 赔偿金额1%
          totalCost: 0, // 综合成本，需要计算
          costRate: 0, // 单人成本率，需要计算
          remarks: hasOrder ? '有订单项目' : '无订单项目'
        });
      }
    });
    
    // 计算综合成本和成本率
    outputValueData.forEach(item => {
      item.totalCost = item.salaryCost + item.socialInsurance + item.otherFees + 
                      item.commercialInsurance + item.equipmentCost + item.compensationAmount;
      item.costRate = item.monthlyOutput > 0 ? (item.totalCost / item.monthlyOutput * 100).toFixed(2) : 0;
    });
    
    return outputValueData;
  };

  const allOutputValueData = generateOutputValueData();
  
  // 筛选数据
  const filteredData = allOutputValueData.filter(item => {
    const matchesSearch = (item.subProjectName || '').toLowerCase().includes(searchText.toLowerCase()) ||
                         (item.name || '').toLowerCase().includes(searchText.toLowerCase()) ||
                         (item.employeeId || '').toLowerCase().includes(searchText.toLowerCase());
    const matchesStatus = statusFilter === 'all' || 
                         (statusFilter === 'hasOrder' && item.hasOrder) ||
                         (statusFilter === 'noOrder' && !item.hasOrder);
    return matchesSearch && matchesStatus;
  });

  // 计算统计数据
  const calculateStats = (data) => {
    const total = data.length;
    const hasOrder = data.filter(item => item.hasOrder).length;
    const noOrder = data.filter(item => !item.hasOrder).length;
    const totalOutput = data.reduce((sum, item) => sum + item.monthlyOutput, 0);
    const totalOutputNoTax = data.reduce((sum, item) => sum + item.monthlyOutputNoTax, 0);
    const totalCost = data.reduce((sum, item) => sum + item.totalCost, 0);
    const avgCostRate = data.length > 0 ? data.reduce((sum, item) => sum + parseFloat(item.costRate), 0) / data.length : 0;
    
    return {
      total,
      hasOrder,
      noOrder,
      totalOutput,
      totalOutputNoTax,
      totalCost,
      avgCostRate
    };
  };

  const stats = calculateStats(filteredData);

  // 产值表格列定义
  const outputValueColumns = [
    {
      title: '序号',
      dataIndex: 'serialNumber',
      key: 'serialNumber',
      width: 80,
      fixed: 'left'
    },
    {
      title: '工号',
      dataIndex: 'employeeId',
      key: 'employeeId',
      width: 100,
      fixed: 'left'
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 100,
      fixed: 'left'
    },
    {
      title: '员工类型',
      dataIndex: 'employeeType',
      key: 'employeeType',
      width: 120,
      render: (type) => {
        const colors = {
          '公司自由人': 'blue',
          '正式员工': 'green',
          '外协人员': 'orange',
          '临时工': 'red'
        };
        return (
          <Tag color={colors[type]}>
            {type}
          </Tag>
        );
      }
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      key: 'projectName',
      width: 200
    },
    {
      title: '账期',
      dataIndex: 'accountPeriod',
      key: 'accountPeriod',
      width: 100
    },
    {
      title: '项目编号',
      dataIndex: 'projectCode',
      key: 'projectCode',
      width: 120
    },
    {
      title: '项目经理',
      dataIndex: 'projectManager',
      key: 'projectManager',
      width: 120
    },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department',
      width: 120
    },
    {
      title: '项目地',
      dataIndex: 'projectLocation',
      key: 'projectLocation',
      width: 100
    },
    {
      title: '入职时间',
      dataIndex: 'joinDate',
      key: 'joinDate',
      width: 120
    },
    {
      title: '入项时间',
      dataIndex: 'projectJoinDate',
      key: 'projectJoinDate',
      width: 120
    },
    {
      title: '离项时间',
      dataIndex: 'projectLeaveDate',
      key: 'projectLeaveDate',
      width: 120
    },
    {
      title: '离职时间',
      dataIndex: 'resignationDate',
      key: 'resignationDate',
      width: 120
    },
    {
      title: '业务类型',
      dataIndex: 'businessType',
      key: 'businessType',
      width: 100
    },
    {
      title: '是否有订单',
      dataIndex: 'hasOrder',
      key: 'hasOrder',
      width: 120,
      render: (hasOrder) => (
        hasOrder ? 
        <Tag icon={<CheckOutlined />} color="success">有订单</Tag> : 
        <Tag icon={<CloseOutlined />} color="error">无订单</Tag>
      )
    },
    {
      title: '单价（含税）',
      dataIndex: 'unitPriceWithTax',
      key: 'unitPriceWithTax',
      width: 120,
      render: (value) => <Text>¥{value.toLocaleString()}</Text>
    },
    {
      title: '工作时长',
      dataIndex: 'workHours',
      key: 'workHours',
      width: 100,
      render: (value) => <Text>{value}h</Text>
    },
    {
      title: '扣减',
      dataIndex: 'deduction',
      key: 'deduction',
      width: 100,
      render: (value) => <Text>¥{value.toLocaleString()}</Text>
    },
    {
      title: '当月产值',
      dataIndex: 'monthlyOutput',
      key: 'monthlyOutput',
      width: 120,
      render: (value) => <Text strong>¥{value.toLocaleString()}</Text>
    },
    {
      title: '当月产值（不含税）',
      dataIndex: 'monthlyOutputNoTax',
      key: 'monthlyOutputNoTax',
      width: 150,
      render: (value) => <Text>¥{value.toLocaleString()}</Text>
    },
    {
      title: '工资成本',
      dataIndex: 'salaryCost',
      key: 'salaryCost',
      width: 120,
      render: (value) => <Text>¥{value.toLocaleString()}</Text>
    },
    {
      title: '企业社保公积金',
      dataIndex: 'socialInsurance',
      key: 'socialInsurance',
      width: 150,
      render: (value) => <Text>¥{value.toLocaleString()}</Text>
    },
    {
      title: '其他费用',
      dataIndex: 'otherFees',
      key: 'otherFees',
      width: 120,
      render: (value) => <Text>¥{value.toLocaleString()}</Text>
    },
    {
      title: '商保',
      dataIndex: 'commercialInsurance',
      key: 'commercialInsurance',
      width: 100,
      render: (value) => <Text>¥{value.toLocaleString()}</Text>
    },
    {
      title: '设备费用',
      dataIndex: 'equipmentCost',
      key: 'equipmentCost',
      width: 120,
      render: (value) => <Text>¥{value.toLocaleString()}</Text>
    },
    {
      title: '赔偿金额',
      dataIndex: 'compensationAmount',
      key: 'compensationAmount',
      width: 120,
      render: (value) => <Text>¥{value.toLocaleString()}</Text>
    },
    {
      title: '综合成本',
      dataIndex: 'totalCost',
      key: 'totalCost',
      width: 120,
      render: (value) => <Text strong>¥{value.toLocaleString()}</Text>
    },
    {
      title: '单人成本率',
      dataIndex: 'costRate',
      key: 'costRate',
      width: 120,
      render: (value) => <Text>{value}%</Text>
    },
    {
      title: '备注',
      dataIndex: 'remarks',
      key: 'remarks',
      width: 150
    }
  ];

  return (
    <div>
      {/* 统计指标卡片 */}
      <div style={{ overflowX: 'auto', marginBottom: 16 }}>
        <div style={{ display: 'flex', minWidth: 'max-content' }}>
          <div style={{ minWidth: '150px', marginRight: 16 }}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic
                title="总人数"
                value={stats.total}
                prefix={<DollarOutlined />}
                valueStyle={{ fontSize: '24px', fontWeight: 'bold' }}
              />
            </Card>
          </div>
          <div style={{ minWidth: '150px', marginRight: 16 }}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic
                title="有订单人数"
                value={stats.hasOrder}
                valueStyle={{ color: '#52c41a', fontSize: '24px', fontWeight: 'bold' }}
              />
            </Card>
          </div>
          <div style={{ minWidth: '150px', marginRight: 16 }}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic
                title="无订单人数"
                value={stats.noOrder}
                valueStyle={{ color: '#ff4d4f', fontSize: '24px', fontWeight: 'bold' }}
              />
            </Card>
          </div>
          <div style={{ minWidth: '150px', marginRight: 16 }}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic
                title="平均成本率"
                value={stats.avgCostRate}
                precision={2}
                suffix="%"
                valueStyle={{ color: '#faad14', fontSize: '24px', fontWeight: 'bold' }}
              />
            </Card>
          </div>
          <div style={{ minWidth: '180px', marginRight: 16 }}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic
                title="总产值（含税）"
                value={stats.totalOutput}
                precision={2}
                prefix="¥"
                valueStyle={{ color: '#1890ff', fontSize: '24px', fontWeight: 'bold' }}
              />
            </Card>
          </div>
          <div style={{ minWidth: '180px', marginRight: 16 }}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic
                title="总产值（不含税）"
                value={stats.totalOutputNoTax}
                precision={2}
                prefix="¥"
                valueStyle={{ color: '#52c41a', fontSize: '24px', fontWeight: 'bold' }}
              />
            </Card>
          </div>
          <div style={{ minWidth: '150px' }}>
            <Card size="small" style={{ textAlign: 'center' }}>
              <Statistic
                title="总成本"
                value={stats.totalCost}
                precision={2}
                prefix="¥"
                valueStyle={{ color: '#faad14', fontSize: '24px', fontWeight: 'bold' }}
              />
            </Card>
          </div>
        </div>
      </div>
      
      {/* 筛选区域 */}
      <Card style={{ marginBottom: 16 }}>
        <Space>
          <Input
            placeholder="按项目名称、姓名或工号搜索"
            prefix={<SearchOutlined />}
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            style={{ width: 300 }}
          />
          
          <Select
            placeholder="按订单状态筛选"
            style={{ width: 150 }}
            value={statusFilter}
            onChange={setStatusFilter}
          >
            <Option value="all">全部状态</Option>
            <Option value="hasOrder">有订单</Option>
            <Option value="noOrder">无订单</Option>
          </Select>
          
          <Button 
            onClick={() => {
              setSearchText('');
              setStatusFilter('all');
            }}
          >
            重置筛选
          </Button>
        </Space>
      </Card>
      
      {/* 产值表格 */}
      <Table
        columns={outputValueColumns}
        dataSource={filteredData}
        rowKey="id"
        pagination={{ pageSize: 10 }}
        scroll={{ x: 4000 }}
        bordered
        size="middle"
      />
    </div>
  );
};

export { OutputValueTab };